package org.lwxyz.service;

import org.lwxyz.Common.CoinType;
import org.lwxyz.Common.Status;
import org.lwxyz.entity.Coin;
import org.lwxyz.tools.mail.MailUtils;
import org.lwxyz.tools.mail.entity.Mail;
import org.lwxyz.utils.JsonUtils;
import org.lwxyz.utils.StringUtil;
import org.lwxyz.utils.file.FileUtil;
import org.lwxyz.utils.redis.JedisUtil;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.io.File;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yuwei
 * @version 1.0-SNAPSHOT
 * @description
 * @date
 */
@Service
public class CoinService {

    /**
     * 触底标志
     */
    public static int waveFlag = 0;

    /**
     * 涨跌标志
     */
    public static int wave = 0;

    private static Boolean flag = true;

    /**
     * 发送邮件标志
     */
    private static Boolean mailFlag = true;

    public static void analysis() {
        try {
            Jedis jedis = JedisUtil.getDefaultJedis();
            while ("start".equals(Status.STATUS)) {
                TimeUnit.MILLISECONDS.sleep(3000);
                String result = FileUtil.readLastLine(new File("/www/python/WebSocket-API-demos/Websocket-Python3-demo/1.txt"),"GBK");
                Map<String, Object> map = JsonUtils.json2Map(result);
                String ch = StringUtil.toString(map.get("rep"));
                System.out.println("类型：" + ch);
                // 获取到数据
                if (StringUtil.isNotBlank(ch)) {
                    String tick = StringUtil.toString(map.get("data"));
                    Map<String, Object> tickMap = JsonUtils.json2Map(tick);
                    // 开盘
                    BigDecimal open = new BigDecimal(StringUtil.toString(tickMap.get("open")));
                    // Double open = Double.parseDouble(NumberUtil.subZeroAndDot(StringUtil.toString(tickMap.get("open"))));
                    // 当前
                    BigDecimal current = new BigDecimal(StringUtil.toString(tickMap.get("close")));
                    // Double current = Double.parseDouble(NumberUtil.subZeroAndDot(StringUtil.toString(tickMap.get("close"))));
                    // 最低
                    BigDecimal low = new BigDecimal(StringUtil.toString(tickMap.get("low")));
                    // Double low = Double.parseDouble(NumberUtil.subZeroAndDot(StringUtil.toString(tickMap.get("low"))));
                    // 最高
                    BigDecimal high = new BigDecimal(StringUtil.toString(tickMap.get("high")));
                    // Double high = Double.parseDouble(NumberUtil.subZeroAndDot(StringUtil.toString(tickMap.get("high"))));
                    // 获取jedis(默认本地redis)

                    exist(jedis,ch + "_open", open);
                    exist(jedis,ch + "_current", current);
                    Double dbLow = get(jedis, ch + "low");
                    Double dbHigh = get(jedis, ch + "high");
                    if (low.doubleValue() < dbLow.doubleValue()) {  // 触底，猛跌
                        waveFlag = -1;
                    } else if (high.doubleValue() > dbHigh.doubleValue()) { // 登顶，猛涨
                        waveFlag = 1;
                    }
                    exist(jedis,ch + "_low", low);
                    exist(jedis,ch + "_high", high);
                    if (current.doubleValue() < open.doubleValue()) {   // 对比开盘时，在跌
                        wave = -1;
                    } else if (current.doubleValue() > open.doubleValue()) {    // 对比开盘时，在涨
                        wave = 1;
                    }
                    double waveRate = (current.doubleValue() - open.doubleValue()) / open.doubleValue();
                    Coin coin = new Coin(wave, waveFlag, waveRate, open, current, low, high);
                    System.out.println("coin：" + JsonUtils.obj2JsonString(coin));
                    // 猛涨，并且对比开盘时涨幅超过15%
                    if (waveFlag == 1 && (waveRate > 0.15 || flag)) {
                        if (CoinType.THETA.equals(ch)) {
                            coin.setName("THETA在猛涨");
                            mail(coin);
                        } else if (CoinType.SMT.equals(ch)) {
                            coin.setName("SMT在猛涨");
                            mail(coin);
                        }
                        mailFlag = false;
                    } else if (waveFlag == -1 && (waveRate < -0.15 || flag)) {
                        if (CoinType.THETA.equals(ch)) {
                            coin.setName("THETA在猛跌");
                            mail(coin);
                        } else if (CoinType.SMT.equals(ch)) {
                            coin.setName("SMT在猛跌");
                            mail(coin);
                        }
                        mailFlag = false;
                    } else {
                        // 处于正常状态， 下次猛涨或者猛跌将会发送邮件
                        mailFlag = true;
                    }
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void mail(Coin coin) throws Exception {
        if (!mailFlag) {    // 当长期处于猛涨或者猛跌状态的时候不需要发送邮件
            return;
        }
        System.out.println();
        System.out.println("准备发送邮件");
        Mail mail = new Mail();
        mail.setSubject(coin.getName());
        StringBuffer context = new StringBuffer();
        context.append("<table border='1px' align='center'><tr><th width='100px'>币种</th><th width='100px'>状态</th><th width='100px'>幅度</th><th width='100px'>当前价</th><th width='100px'>开盘价</th><th width='100px'>最高价</th><th width='100px'>最低价</th></tr>");
        context.append("<tr>");
        context.append("<td>");
        context.append(coin.getName().replace("在猛涨","").replace("在猛跌",""));
        context.append("</td>");
        context.append("<td>");
        context.append(coin.getName().replace("THETA在","").replace("SMT在",""));
        context.append("</td>");
        context.append("<td>");
        context.append(coin.getRate());
        context.append("</td>");
        context.append("<td>");
        context.append(coin.getCurrent());
        context.append("</td>");
        context.append("<td>");
        context.append(coin.getOpen());
        context.append("</td>");
        context.append("<td>");
        context.append(coin.getHigh());
        context.append("</td>");
        context.append("<td>");
        context.append(coin.getLow());
        context.append("</td>");
        context.append("</tr>");
        context.append("</table>");
        mail.setContext(context.toString());
        // 邮件通知
        System.out.println("邮件发送成功");
        MailUtils.sendMail(1, "yuwei@lwxyz.org", mail);
    }

    /**
     * 获取redis存的值
     * @param jedis
     * @param key
     * @return
     */
    public static Double get(Jedis jedis, String key) {
        if (jedis.exists(key)) {
            return Double.parseDouble(jedis.get(key));
        }
        return 0.0;
    }

    /**
     * 判断是否存在
     * 存在则对比是不是最新的
     * 不是最新的更新
     * 不存在直接保存
     * @param jedis
     * @param key
     * @param value
     * @return
     */
    public static void exist(Jedis jedis, String key, BigDecimal value) {
        if (jedis.exists(key)) {
            BigDecimal dbValue = new BigDecimal(jedis.get(key));
            if (dbValue.compareTo(value) != 0) {
                jedis.set(key, value.toString());
            }
        } else {
            jedis.set(key, value.toString());
        }
    }
}

/*
"tick": {
    "id": K线id,
    "amount": 成交量,
    "count": 成交笔数,
    "open": 开盘价,
    "close": 收盘价,当K线为最晚的一根时，是最新成交价
    "low": 最低价,
    "high": 最高价,
    "vol": 成交额, 即 sum(每一笔成交价 * 该笔的成交量)
  }
 */
